import type { FC } from 'react'
import { useRef } from 'react'
import { Space, Button, Avatar, message } from 'antd'
import useArtAddStore, { setCurrent, Move, setArticleCover, selectCover } from '@/store/art-add-store.ts'

const ArticleCover: FC = () => {
  const iptRef = useRef<HTMLInputElement>(null)
  const coverURL = useArtAddStore(selectCover)

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.currentTarget.files
    if (!files || files.length === 0) return
    if (files[0].size > 1024 * 1024 * 2) return message.error('封面图片不能大于2M！')
    // 持久化存储文章封面
    setArticleCover(files[0])
  }

  const handleNext = () => {
    if (!coverURL) return message.error('请选择文章封面！')
    setCurrent()
  }

  return (
    <>
      <Space direction="vertical">
        {/* 按需渲染文章封面 */}
        {coverURL ? (
          <Avatar size={300} shape="square" src={coverURL} />
        ) : (
          <Avatar size={300} shape="square">
            请选择文章封面
          </Avatar>
        )}

        <Space direction="horizontal">
          <Button type="primary" onClick={() => setCurrent(Move.prev)}>
            上一步
          </Button>
          <Button type="primary" onClick={() => iptRef.current?.click()}>
            选择封面
          </Button>
          <Button type="primary" onClick={handleNext}>
            下一步
          </Button>
          <input type="file" accept="image/*" style={{ display: 'none' }} ref={iptRef} onChange={handleFileChange} />
        </Space>
      </Space>
    </>
  )
}

export default ArticleCover
